package com.lottery.ruok.lottrey.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.PrizeListActivity;
import com.lottery.ruok.lottrey.adapter.MyPagerAdapter;
import com.lottery.ruok.lottrey.adapter.PL3AndFC3DListViewAdapter;
import com.lottery.ruok.lottrey.adapter.PrizeNumberAdapter;
import com.lottery.ruok.lottrey.adapter.PrizeNumberAdapter_ahk3;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.ListToTop;
import com.lottery.ruok.lottrey.eventbusObject.Tabs;
import com.lottery.ruok.lottrey.interfaces.PrizeNumberListViewLoadMoreListener;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.LotteryStatOneRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.LotteryStatOneResponse;
import com.lottery.ruok.lottrey.ui.widget.LoadMoreListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.NoScrollViewPager;

/**
 * Created by ASUS on 2017/7/27.
 */

public class PrizeNumberFragment extends BaseFragment {
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.ll_tab)
    LinearLayout llTab;
    @BindView(R.id.include_pl3_tab_layout)
    LinearLayout includePl3TabLayout;
    @BindView(R.id.include_ahk3_tab_layout)
    LinearLayout includeAhk3TabLayout;
    @BindView(R.id.fish_label)
    TextView fish_label;
    private ArrayList<View> mViewList = new ArrayList<>();
    private LotteryStatOneResponse data;
    private PrizeNumberAdapter prizeNumberAdapter;
    private Map<ListView, BaseAdapter> adapterCache = new HashMap<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //在配置变化的时候将这个fragment保存下来
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.prize_number_fragment, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }
/*

    public void getList() {
        if (mViewList.size() > 0) {
            adapterCache.clear();
            if (getActivity() != null) {
                if (data.getItem_code().equals("ahk3") || data.getItem_code().equals("jiangsuk3") || data.getItem_code().equals("ctjiangsuk3") || data.getItem_code().equals("jsk3")) {
                    for (View view : mViewList) {
                        LoadMoreListView listView = view.findViewById(R.id.listView);
                        PrizeNumberAdapter_ahk3 prizeNumberAdapter_ahk3 = new PrizeNumberAdapter_ahk3(getActivity(), data);
                        PrizeNumberAdapter_ahk3 prizeNumberAdapter_ahk3 = new PrizeNumberAdapter_ahk3(getActivity(), mLotteryStatOneResponse,data.getItem_code());
                        listView.setAdapter(prizeNumberAdapter_ahk3);
                        adapterCache.put(listView, prizeNumberAdapter_ahk3);
                    }
                } else if (data.getItem_code().equals("pl3") || data.getItem_code().equals("fc3d") || data.getItem_code().equals("jspl3") || data.getItem_code().equals("jsfc3d")) {
                    for (View view : mViewList) {
                        LoadMoreListView listView = view.findViewById(R.id.listView);
                        PL3AndFC3DListViewAdapter prizeNumberAdapter_ahk3 = new PL3AndFC3DListViewAdapter(getActivity(), data);
                        listView.setAdapter(prizeNumberAdapter_ahk3);
                        adapterCache.put(listView, prizeNumberAdapter_ahk3);
                    }
                } else {
                    String[] b = data.getTwotab().split(",");
                    if (b.length == mViewList.size()) {
                        for (int i = 0; i < b.length; i++) {
                            LoadMoreListView listView = mViewList.get(i).findViewById(R.id.listView);
                            PrizeNumberAdapter prizeNumberAdapter = new PrizeNumberAdapter(b[i], getActivity(), data);
                            listView.setAdapter(prizeNumberAdapter);
                            adapterCache.put(listView, prizeNumberAdapter);
                        }
                    }
                }
            }
        }
    }
*/

    public void setData(LotteryStatOneResponse data) {
        this.data = data;
        if (llTab != null && data.getServer_time().equals(((PrizeListActivity) getActivity()).currentDate)) {
            init();
        }
    }

    private void init() {
        mViewList.clear();
        adapterCache.clear();
        if (data != null) {
            if (Common.isOfficialK3(data.getItem_code())||Common.isK3(data.getItem_code())) {
                llTab.setVisibility(View.GONE);
                includePl3TabLayout.setVisibility(View.GONE);
                includeAhk3TabLayout.setVisibility(View.VISIBLE);
                if(Common.isOfficialK3(data.getItem_code())){
                    fish_label.setVisibility(View.GONE);
                }else{
                    fish_label.setVisibility(View.VISIBLE);
                }
                final LoadMoreListView listView = (LoadMoreListView) getActivity().getLayoutInflater().inflate(R.layout.custom_tab_prize2, null);
                listView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        listView.setHaveMoreData(true);
                        fragmentGetList(data.getItem_code(), ((PrizeListActivity) getActivity()).currentDate, data.getIssue_list().size(), 50, new PrizeNumberListViewLoadMoreListener() {
                            @Override
                            public void onMoreData() {
                                listView.onLoadComplete();
                                for (ListView view : adapterCache.keySet()) {
                                    adapterCache.get(view).notifyDataSetChanged();
                                }
                            }

                            @Override
                            public void onNoMoreData() {
                                listView.setHaveMoreData(false);
                            }
                        });
                    }

                    @Override
                    public void onScroll(int index) {
                        if (index > 10) {
                            ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.VISIBLE);
                        } else {
                            ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.GONE);
                        }
                    }
                });
                PrizeNumberAdapter_ahk3 prizeNumberAdapter_ahk3 = new PrizeNumberAdapter_ahk3(getActivity(), data,data.getItem_code());
                listView.setAdapter(prizeNumberAdapter_ahk3);
                adapterCache.put(listView, prizeNumberAdapter_ahk3);
                mViewList.add(listView);
                MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
                viewPager.setAdapter(mAdapter);

            } else if (Common.PL3_ALLIED.contains(data.getItem_code())) {
                llTab.setVisibility(View.GONE);
                includeAhk3TabLayout.setVisibility(View.GONE);
                includePl3TabLayout.setVisibility(View.VISIBLE);

                final LoadMoreListView listView = (LoadMoreListView) getActivity().getLayoutInflater().inflate(R.layout.custom_tab_prize2, null);
                listView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        listView.setHaveMoreData(true);
                        fragmentGetList(data.getItem_code(), ((PrizeListActivity) getActivity()).currentDate, data.getIssue_list().size(), 50, new PrizeNumberListViewLoadMoreListener() {
                            @Override
                            public void onMoreData() {
                                listView.onLoadComplete();
                                for (ListView view : adapterCache.keySet()) {
                                    adapterCache.get(view).notifyDataSetChanged();
                                }
                            }

                            @Override
                            public void onNoMoreData() {
                                listView.setHaveMoreData(false);
                            }
                        });
                    }

                    @Override
                    public void onScroll(int index) {
                        if (index > 10) {
                            ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.VISIBLE);
                        } else {
                            ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.GONE);
                        }
                    }
                });
                PL3AndFC3DListViewAdapter prizeNumberAdapter_ahk3 = new PL3AndFC3DListViewAdapter(getActivity(), data);
                listView.setAdapter(prizeNumberAdapter_ahk3);
                adapterCache.put(listView, prizeNumberAdapter_ahk3);
                mViewList.add(listView);
                MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
                viewPager.setAdapter(mAdapter);
            } else {
                llTab.setVisibility(View.VISIBLE);
                includeAhk3TabLayout.setVisibility(View.GONE);
                includePl3TabLayout.setVisibility(View.GONE);
                String[] b = data.getTwotab().split(",");
                for (String aB : b) {
                    final LoadMoreListView listView = (LoadMoreListView) getActivity().getLayoutInflater().inflate(R.layout.custom_tab_prize2, null);
                    prizeNumberAdapter = new PrizeNumberAdapter(aB, getActivity(), data);
                    listView.setAdapter(prizeNumberAdapter);
                    adapterCache.put(listView, prizeNumberAdapter);
                    listView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
                        @Override
                        public void onLoadMore() {
                            listView.setHaveMoreData(true);
                            fragmentGetList(data.getItem_code(), ((PrizeListActivity) getActivity()).currentDate, data.getIssue_list().size(), 50, new PrizeNumberListViewLoadMoreListener() {
                                @Override
                                public void onMoreData() {
                                    listView.onLoadComplete();
                                    for (ListView view : adapterCache.keySet()) {
                                        adapterCache.get(view).notifyDataSetChanged();
                                    }
                                }

                                @Override
                                public void onNoMoreData() {
                                    listView.setHaveMoreData(false);
                                }
                            });
                        }

                        @Override
                        public void onScroll(int index) {
                            if (index > 10) {
                                ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.VISIBLE);
                            } else {
                                ((PrizeListActivity) getActivity()).gotoTop.setVisibility(View.GONE);
                            }
                        }
                    });
                    mViewList.add(listView);
                }
                MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
                viewPager.setAdapter(mAdapter);
                tabs.setupWithViewPager(viewPager);

                for (int i = 0; i < tabs.getTabCount(); i++) {
                    TabLayout.Tab tab = tabs.getTabAt(i);
                    View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab_1, null);
                    TextView name = view1.findViewById(R.id.name);
                    if (i != 0) {
                        name.setBackgroundResource(R.color.bg_white);
                        name.setTextColor(Color.parseColor("#856c9c"));
                    } else {
                        name.setBackgroundResource(R.drawable.bg_corners_100_1);
                        name.setTextColor(Color.parseColor("#661dac"));
                    }
                    name.setText(b[i]);

                    tab.setCustomView(view1);
                }

                viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        for (int i = 0; i < tabs.getTabCount(); i++) {
                            if (i == position) {
                                tabs.getTabAt(i).getCustomView().findViewById(R.id.name).setBackgroundResource(R.drawable.bg_corners_100_1);
                                ((TextView) (tabs.getTabAt(i).getCustomView().findViewById(R.id.name))).setTextColor(Color.parseColor("#661dac"));
                            } else {
                                tabs.getTabAt(i).getCustomView().findViewById(R.id.name).setBackgroundResource(R.color.bg_white);
                                ((TextView) (tabs.getTabAt(i).getCustomView().findViewById(R.id.name))).setTextColor(Color.parseColor("#856c9c"));
                            }
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setTabs(Tabs tabs) {
        if (Common.isOfficialK3(data.getItem_code())||Common.isK3(data.getItem_code())) {
            if (mViewList.size() > 0) {
                LoadMoreListView listView = mViewList.get(0).findViewById(R.id.listView);
                if (tabs.isCanListScroll()) {
                    listView.setCanListScroll(true);
                } else {
                    listView.setCanListScroll(false);
                }
            }
        } else if (Common.PL3_ALLIED.contains(data.getItem_code())) {
            if (mViewList.size() > 0) {
                LoadMoreListView listView = mViewList.get(0).findViewById(R.id.listView);
                if (tabs.isCanListScroll()) {
                    listView.setCanListScroll(true);
                } else {
                    listView.setCanListScroll(false);
                }
            }
        } else {
            String[] b = data.getTwotab().split(",");
            for (int i = 0; i < b.length; i++) {
                LoadMoreListView listView = mViewList.get(i).findViewById(R.id.listView);
                if (tabs.isCanListScroll()) {
                    listView.setCanListScroll(true);
                } else {
                    listView.setCanListScroll(false);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void gotoTop(ListToTop listToTop) {
        if (Common.isOfficialK3(data.getItem_code())||Common.isK3(data.getItem_code())) {
            if (mViewList.size() > 0) {
                LoadMoreListView listView = mViewList.get(0).findViewById(R.id.listView);
                listView.setSelection(0);
            }
        } else if (Common.PL3_ALLIED.contains(data.getItem_code())) {
            if (mViewList.size() > 0) {
                LoadMoreListView listView = mViewList.get(0).findViewById(R.id.listView);
                listView.setSelection(0);
            }

        } else {
            String[] b = data.getTwotab().split(",");
            for (int i = 0; i < b.length; i++) {
                LoadMoreListView listView = mViewList.get(i).findViewById(R.id.listView);
                listView.setSelection(0);
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    private void fragmentGetList(String code, String date, int index, int size, final PrizeNumberListViewLoadMoreListener prizeNumberListViewLoadMoreListener) {
        RetrofitBase.getRetrofit().create(LotteryStatOneRequest.class).getResult(code, date, index, size)
                .compose(RxHelper.<LotteryStatOneResponse>handleResult())
                .subscribeWith(new RxSubscribe<LotteryStatOneResponse>(getActivity()) {
                    @Override
                    protected void _onNext(LotteryStatOneResponse lotteryStatOneResponse) {
                        List<LotteryStatOneResponse.IssueListBean> responset = lotteryStatOneResponse.getIssue_list();
                        List<LotteryStatOneResponse.IssueListBean> total = data.getIssue_list();
                        Iterator<LotteryStatOneResponse.IssueListBean> iterator = responset.iterator();
                        while (iterator.hasNext()) {
                            LotteryStatOneResponse.IssueListBean next = iterator.next();
                            if (total.contains(next)) {
                                iterator.remove();
                            }
                        }
                        data.getIssue_list().addAll(responset);
                        if (lotteryStatOneResponse.getIssue_list().size() > 0) {
                            prizeNumberListViewLoadMoreListener.onMoreData();
                        } else {
                            prizeNumberListViewLoadMoreListener.onNoMoreData();
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
